//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import { useState, useMemo, useEffect } from 'react';
import React from 'react';
import s from './index.module.less';
import { useHistory, useLocation } from 'react-router-dom';
import { WORKBENCH_PATH } from '@/utils/constant';
import { useStores } from '@/hooks';
import Card from './components/Card';
import InfoCount from './components/InfoCount';
import { Modal, Popover, Segmented, Select, Space, Tabs } from 'antd';
import { observer } from 'mobx-react';
import { AppstoreOutlined, BarsOutlined, CloudServerOutlined, CreditCardOutlined, EditFilled, ExportOutlined, FolderOutlined, InfoCircleOutlined, MoreOutlined, WarningOutlined } from '@ant-design/icons';
import Button from '@/components/Button';
import UserAppList from './UserAppList';
import LocalRepoList from './LocalRepoList';
import AddRepoModal from './components/localrepo/AddRepoModal';
import { USER_TYPE_ATOM_GIT, USER_TYPE_GIT_CODE, USER_TYPE_GITEE } from '@/api/user';
import iconAtomgit from '@/assets/allIcon/icon-atomgit.png';
import iconGitee from '@/assets/allIcon/icon-gitee.png';
import iconGitCode from '@/assets/allIcon/icon-gitcode.png';
import AtomGitPanel from './AtomGitPanel';
import { open as shell_open } from '@tauri-apps/api/shell';
import GitConfigModal from './components/GitConfigModal';
import { install_lfs } from "@/api/git_wrap";
import GiteePanel from './GiteePanel';
import EditMemoModal from './components/usermemo/EditMemoModal';
import MemoList from './components/usermemo/MemoList';
import GitCodePanel from './GitCodePanel';
import { request } from '@/utils/request';
import { get_my_todo_status } from '@/api/project_issue';
import MyTodoList from './components/MyTodoList';
import { APP_TYPE_ALL, APP_TYPE_GRPC, APP_TYPE_MONGO, APP_TYPE_MYSQL, APP_TYPE_POSTGRES, APP_TYPE_REDIS, APP_TYPE_SSH } from '@/api/appstore';
import EditServModal from './components/userserv/EditServModal';
import UserServerList from './components/userserv/UserServerList';
import AppStorePanel from './AppStorePanel';
import DebugMinAppModal from '@/components/MinApp/DebugMinAppModal';
import WelcomeInfo from './components/WelcomeInfo';
import { get_assistant_mode, set_assistant_mode } from '@/api/local_repo';


const Workbench: React.FC = () => {
  const location = useLocation();
  const history = useHistory();
  const urlParams = new URLSearchParams(location.search);

  const userStore = useStores('userStore');
  const projectStore = useStores('projectStore');
  const orgStore = useStores('orgStore');
  const localRepoStore = useStores("localRepoStore");
  const appStore = useStores("appStore");

  const tab = urlParams.get('tab') ?? (userStore.sessionId == "" ? "welcome" : "localRepo");

  const [showAddRepoModal, setShowAddRepoModal] = useState(false);
  const [showGitConfigModal, setShowGitConfigModal] = useState(false);
  const [showGitLfsConfigModal, setShowGitLfsConfigModal] = useState(false);

  const [showAddMemoModal, setShowAddMemoModal] = useState(false);
  const [memoTagList, setMemoTagList] = useState<string[]>([]);
  const [curMemoTagList, setCurMemoTagList] = useState<string[]>([]);
  const [memoDataVersion, setMemoDataVersion] = useState(0);

  const [showAddServModal, setShowAddServModal] = useState(false);
  const [servDataVersion, setServDataVersion] = useState(0);
  const [curServType, setCurServType] = useState(APP_TYPE_ALL);

  const [todoIssueCount, setTodoIssueCount] = useState(0);

  const [minAppSegValue, setMinAppSegValue] = useState<"myApp" | "appStore">("myApp");
  const [showMinAppDebug, setShowMinAppDebug] = useState(false);

  const [assistantMode, setAssistantMode] = useState<"simple" | "expert">("simple");

  const loadTodoIssueCount = async () => {
    if (userStore.sessionId == "") {
      return;
    }
    const res = await request(get_my_todo_status({
      session_id: userStore.sessionId,
    }));
    setTodoIssueCount(res.total_count);
  };

  const loadAssistantMode = async () => {
    const mode = await get_assistant_mode();
    setAssistantMode(mode);
  };


  useMemo(() => {
    projectStore.setCurProjectId('');
    orgStore.setCurOrgId("");
  }, []);

  useEffect(() => {
    if (userStore.sessionId == "" && ["atomGit", "gitCode", "gitee", "userMemo", "userServer", "todo"].includes(tab)) {
      history.push(`${WORKBENCH_PATH}?tab=welcome`);
    }
  }, [userStore.sessionId]);

  useEffect(() => {
    if (userStore.sessionId != "") {
      loadTodoIssueCount();
    }
    loadAssistantMode();
  }, [userStore.sessionId]);

  useEffect(() => {
    setMinAppSegValue("myApp");
  }, [tab]);

  return (
    <div className={s.workbench_wrap}>
      <Card className={s.infoCount_wrap} childStyle={{ height: '100%', overflow: "hidden" }}>
        {!userStore.isResetPassword && <InfoCount todoIssueCount={todoIssueCount} showTodoPanel={() => history.push(`${WORKBENCH_PATH}?tab=todo`)} />}
      </Card>
      <Tabs activeKey={tab} className={s.my_wrap} type="card"
        addIcon={<EditFilled title='配置标签' style={{ fontSize: "16px", color: "blue" }} />}
        onChange={key => {
          history.push(`${WORKBENCH_PATH}?tab=${key}`);
        }}
        tabBarStyle={{ marginBottom: "0px" }}
        tabBarExtraContent={
          <div>
            {tab == "userApp" && (
              <Space>
                <Segmented options={[
                  {
                    label: <span style={{ color: minAppSegValue == "myApp" ? "blue" : undefined, fontSize: "16px", fontWeight: 700 }}>已安装</span>,
                    value: "myApp",
                  },
                  {
                    label: <span style={{ color: minAppSegValue == "appStore" ? "blue" : undefined, fontSize: "16px", fontWeight: 700 }}>应用市场</span>,
                    value: "appStore",
                  }
                ]} value={minAppSegValue} onChange={value => setMinAppSegValue(value as "myApp" | "appStore")} />
                <Popover placement="bottom" trigger="click" content={
                  <Space direction="vertical">
                    <Button type="link" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      setShowMinAppDebug(true);
                    }}>调试应用</Button>
                  </Space>
                }>
                  <MoreOutlined style={{ marginRight: "32px" }} />
                </Popover>
              </Space>
            )}
            {tab == "localRepo" && localRepoStore.checkResult != null && (
              <Space>
                {localRepoStore.checkResult.hasGit == false && (
                  <>
                    <Button type="text" style={{ color: "red", fontWeight: 700, fontSize: "14px" }}
                      onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        shell_open("https://git-scm.com/downloads");
                      }}><WarningOutlined />安装Git工具</Button>
                    <Button type="default" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      localRepoStore.checkGitEnv();
                    }}>重新检测</Button>
                  </>
                )}
                {localRepoStore.checkResult.hasGit && localRepoStore.checkResult.hasConfigGit == false && (
                  <Button type="text" style={{ color: "red", fontWeight: 700, fontSize: "14px" }}
                    onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      setShowGitConfigModal(true);
                    }}><WarningOutlined />未配置git用户</Button>
                )}
                {localRepoStore.checkResult.hasGit && localRepoStore.checkResult.hasConfigGit && localRepoStore.checkResult.hasGitLfs == false && (
                  <>
                    <Button type="text" style={{ color: "red", fontWeight: 700, fontSize: "14px" }}
                      onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        shell_open("https://git-lfs.com/");
                      }}><WarningOutlined />安装GitLfs工具</Button>
                    <Button type="default" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      localRepoStore.checkGitEnv();
                    }}>重新检测</Button>
                  </>
                )}
                {localRepoStore.checkResult.hasGit && localRepoStore.checkResult.hasConfigGit && localRepoStore.checkResult.hasGitLfs && localRepoStore.checkResult.hasConfigGitLfs == false && (
                  <Button type="text" style={{ color: "red", fontWeight: 700, fontSize: "14px" }}
                    onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      setShowGitLfsConfigModal(true);
                    }}><WarningOutlined />未配置GitLfs</Button>
                )}
                {localRepoStore.checkResult.hasGit && (
                  <>
                    <span>助手模式:</span>
                    <Segmented options={[
                      {
                        label: "简单",
                        value: "simple",
                      },
                      {
                        label: "专业",
                        value: "expert",
                      }
                    ]} value={assistantMode} onChange={value => {
                      setAssistantMode(value as "simple" | "expert");
                      set_assistant_mode(value as "simple" | "expert");
                    }} />
                  </>
                )}
                {localRepoStore.checkResult.hasGit && (
                  <Button style={{ marginRight: "20px", backgroundColor: localRepoStore.repoExtList.length == 0 ? "orange" : undefined, border: localRepoStore.repoExtList.length == 0 ? "none" : undefined }}
                    onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      setShowAddRepoModal(true);
                    }}>
                    添加代码仓库
                  </Button>
                )}
                <Popover trigger="click" placement="bottom" content={
                  <Space direction="vertical">
                    <Button type="link" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      setShowGitConfigModal(true);
                    }}>配置git用户</Button>
                  </Space>
                }>
                  <MoreOutlined style={{ marginRight: "32px" }} />
                </Popover>
              </Space>
            )}
            {tab == "atomGit" && (
              <Space>
                <Button type="link" onClick={e => {
                  e.stopPropagation();
                  e.preventDefault();
                  shell_open("https://atomgit.com/project/new");
                }}>
                  <span style={{ fontSize: "14px", fontWeight: 600 }}>
                    创建项目&nbsp;<ExportOutlined />
                  </span>
                </Button>
                <Popover trigger="click" placement="bottom" content={
                  <div style={{ padding: "10px 10px" }}>
                    <Button type="link" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      shell_open("https://docs.atomgit.com");
                    }}>查看帮助&nbsp;<ExportOutlined /></Button>
                  </div>
                }>
                  <MoreOutlined style={{ marginRight: "32px" }} />
                </Popover>
              </Space>
            )}
            {tab == "gitee" && (
              <Space>
                <Button type="link" onClick={e => {
                  e.stopPropagation();
                  e.preventDefault();
                  shell_open("https://gitee.com/projects/new");
                }}>
                  <span style={{ fontSize: "14px", fontWeight: 600 }}>
                    创建项目&nbsp;<ExportOutlined />
                  </span>
                </Button>
                <Popover trigger="click" placement="bottom" content={
                  <div style={{ padding: "10px 10px" }}>
                    <Button type="link" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      shell_open("https://help.gitee.com/");
                    }}>查看帮助&nbsp;<ExportOutlined /></Button>
                  </div>
                }>
                  <MoreOutlined style={{ marginRight: "32px" }} />
                </Popover>
              </Space>
            )}
            {tab == "userMemo" && (
              <Space style={{ marginRight: "32px" }} size="large">
                {memoTagList.length > 0 && (
                  <Select value={curMemoTagList} mode='multiple' onChange={value => setCurMemoTagList(value)} style={{ width: "200px" }}
                    placeholder="请选择标签" allowClear>
                    {memoTagList.map(tag => (
                      <Select.Option key={tag} value={tag}>{tag}</Select.Option>
                    ))}
                  </Select>
                )}
                <Button type="primary" onClick={e => {
                  e.stopPropagation();
                  e.preventDefault();
                  setShowAddMemoModal(true);
                }}>创建备忘录</Button>
              </Space>
            )}
            {tab == "userServer" && (
              <Space style={{ marginRight: "32px" }} size="large">
                <Select value={curServType} onChange={value => setCurServType(value)} style={{ width: "100px" }}>
                  <Select.Option value={APP_TYPE_ALL}>全部</Select.Option>
                  <Select.Option value={APP_TYPE_SSH}>SSH</Select.Option>
                  <Select.Option value={APP_TYPE_MYSQL}>MYSQL</Select.Option>
                  <Select.Option value={APP_TYPE_POSTGRES}>POSTGRES</Select.Option>
                  <Select.Option value={APP_TYPE_MONGO}>MONGO</Select.Option>
                  <Select.Option value={APP_TYPE_REDIS}>REDIS</Select.Option>
                  <Select.Option value={APP_TYPE_GRPC}>GRPC</Select.Option>
                </Select>
                <Button type="primary" onClick={e => {
                  e.stopPropagation();
                  e.preventDefault();
                  setShowAddServModal(true);
                }}>增加服务</Button>
              </Space>
            )}
          </div>
        }>
        {userStore.sessionId != "" && userStore.userInfo.userType == USER_TYPE_ATOM_GIT && (
          <Tabs.TabPane tab={<h2><img src={iconAtomgit} style={{ width: "14px", marginRight: "10px", marginTop: "-4px" }} />AtomGit</h2>} key="atomGit">
            {tab == "atomGit" && (
              <div className={s.content_wrap}>
                <AtomGitPanel />
              </div>
            )}
          </Tabs.TabPane>
        )}
        {userStore.sessionId != "" && userStore.userInfo.userType == USER_TYPE_GIT_CODE && (
          <Tabs.TabPane tab={<h2><img src={iconGitCode} style={{ width: "14px", marginRight: "10px", marginTop: "-4px" }} />GitCode</h2>} key="gitCode">
            {tab == "gitCode" && (
              <div className={s.content_wrap}>
                <GitCodePanel />
              </div>
            )}
          </Tabs.TabPane>
        )}
        {userStore.sessionId != "" && userStore.userInfo.userType == USER_TYPE_GITEE && (
          <Tabs.TabPane tab={<h2><img src={iconGitee} style={{ width: "14px", marginRight: "10px", marginTop: "-4px" }} />Gitee</h2>} key="gitee">
            {tab == "gitee" && (
              <div className={s.content_wrap}>
                <GiteePanel />
              </div>
            )}
          </Tabs.TabPane>
        )}
        <Tabs.TabPane tab={<h2><FolderOutlined />本地仓库</h2>} key="localRepo">
          {tab == "localRepo" && (
            <div className={s.content_wrap}>
              <LocalRepoList />
            </div>
          )}
        </Tabs.TabPane>

        {appStore.vendorCfg?.work_bench.enable_minapp == true && (
          <Tabs.TabPane tab={<h2 style={{ color: userStore.sessionId == "" ? "#aaa" : undefined }} title={userStore.sessionId == "" ? "需登录状态" : ""}><AppstoreOutlined />微应用</h2>} key="userApp" disabled={userStore.sessionId == ""}>
            {tab == "userApp" && (
              <div className={s.content_wrap}>
                {minAppSegValue == "myApp" && <UserAppList onCount={appCount => {
                  if (appCount == 0) {
                    setMinAppSegValue("appStore");
                  }
                }} />}
                {minAppSegValue == "appStore" && <AppStorePanel />}
              </div>
            )}
          </Tabs.TabPane>
        )}


        {userStore.sessionId != "" && appStore.vendorCfg?.ability.enable_project && userStore.userInfo.featureInfo.enable_project && (
          <Tabs.TabPane tab={<h2><BarsOutlined />当前待办</h2>} key="todo">
            {tab == "todo" && (
              <div className={s.content_wrap}>
                <MyTodoList onCount={newCount => setTodoIssueCount(newCount)} />
              </div>
            )}
          </Tabs.TabPane>
        )}

        {appStore.vendorCfg?.work_bench.enable_user_memo == true && (
          <Tabs.TabPane tab={<h2 style={{ color: userStore.sessionId == "" ? "#aaa" : undefined }} title={userStore.sessionId == "" ? "需登录状态" : ""}><CreditCardOutlined />备忘录</h2>} key="userMemo" disabled={userStore.sessionId == ""}>
            {tab == "userMemo" && (
              <div style={{ height: "calc(100vh - 210px)", overflowY: "scroll", overflowX: "hidden" }}>
                <MemoList curMemoTagList={curMemoTagList} dataVersion={memoDataVersion} onLoadTagList={newTagList => setMemoTagList(newTagList)} />
              </div>
            )}
          </Tabs.TabPane>
        )}
        {appStore.vendorCfg?.work_bench.enable_minapp == true && appStore.vendorCfg?.work_bench.enable_server_list == true && (
          <Tabs.TabPane tab={<h2 style={{ color: userStore.sessionId == "" ? "#aaa" : undefined }} title={userStore.sessionId == "" ? "需登录状态" : ""}><CloudServerOutlined />服务器列表</h2>} key="userServer" disabled={userStore.sessionId == ""}>
            {tab == "userServer" && (
              <div style={{ height: "calc(100vh - 210px)", overflowY: "hidden", overflowX: "hidden" }}>
                <UserServerList servType={curServType} dataVersion={servDataVersion} />
              </div>
            )}
          </Tabs.TabPane>
        )}

        <Tabs.TabPane tab={<h2><InfoCircleOutlined />欢迎使用</h2>} key="welcome">
          {tab == "welcome" && (
            <div className={s.content_wrap}>
              {appStore.vendorCfg?.layout.welcome_page_url == "" && <WelcomeInfo />}
              {appStore.vendorCfg?.layout.welcome_page_url != "" && <iframe src={appStore.vendorCfg?.layout.welcome_page_url ?? ""} width="100%" height="100%" allow='*' />}
            </div>
          )}
        </Tabs.TabPane>

      </Tabs>
      {showAddRepoModal == true && (
        <AddRepoModal onCancel={() => setShowAddRepoModal(false)} onOk={() => {
          localRepoStore.loadRepoList();
          setShowAddRepoModal(false);
        }} />
      )}
      {showGitConfigModal == true && (
        <GitConfigModal onCancel={() => setShowGitConfigModal(false)} onOk={() => {
          setShowGitConfigModal(false);
          localRepoStore.checkGitEnv();
        }} />
      )}
      {showGitLfsConfigModal == true && (
        <Modal open title="配置GitLfs" mask={false}
          okText="执行"
          onCancel={e => {
            e.stopPropagation();
            e.preventDefault();
            setShowGitLfsConfigModal(false);
          }}
          onOk={e => {
            e.stopPropagation();
            e.preventDefault();
            install_lfs().then(() => {
              setShowGitLfsConfigModal(false);
              localRepoStore.checkGitEnv();
            });
          }}>
          是否执行git lfs install?
        </Modal>
      )}
      {showAddMemoModal == true && (
        <EditMemoModal tagList={memoTagList} onCancel={() => setShowAddMemoModal(false)} onOk={() => {
          setShowAddMemoModal(false);
          setMemoDataVersion(memoDataVersion + 1);
        }} />
      )}
      {showAddServModal == true && (
        <EditServModal onCancel={() => setShowAddServModal(false)} onOk={() => {
          setShowAddServModal(false);
          setServDataVersion(servDataVersion + 1);
          setCurServType(APP_TYPE_ALL);
        }} />
      )}
      {showMinAppDebug == true && (
        <DebugMinAppModal onCancel={() => setShowMinAppDebug(false)} onOk={() => setShowMinAppDebug(false)} />
      )}
    </div>
  );
};

export default observer(Workbench);
